/*
 moxl - Modular XML Library
 Copyright (c) 2007, Malcolm Sparks

 This program is free software; you can redistribute it and/or
 modify it under the terms of the GNU General Public License
 as published by the Free Software Foundation; either version 2
 of the License, or (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
package moxl.xpath.parser.types;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import moxl.xpath.XPathContext;
import moxl.xpath.functions.XPathFunctionIllegalArgumentException;
import moxl.xpath.parser.Operand;
import moxl.xpath.parser.states.step.Function;

public class FunctionCall implements NonTerminal, Operand
{
	private String functionName;
	private final List<Operand> args = new ArrayList<Operand>();

	private static final Set<String> nodeTypes = new HashSet<String>();
	static
	{
		nodeTypes.add("comment");
		nodeTypes.add("text");
		nodeTypes.add("processing-instruction");
		nodeTypes.add("node");
	}

	public String getFunctionName()
	{
		return functionName;
	}

	public void setFunctionName(String functionName)
	{
		if (nodeTypes.contains(functionName))
		{
			throw new IllegalArgumentException("Illegal function name, this is a node-type: " + functionName);
		}
		this.functionName = functionName;
	}

	public void addArgument(Operand argExpr)
	{
		args.add(argExpr);
	}

	public Operand[] getArguments()
	{
		return (Operand[]) args.toArray(new Operand[args.size()]);
	}

	public AbstractXPathValue evaluate(XPathContext context) throws XPathEvaluationException
	{
		Function function = context.getFunction(getFunctionName());
		Operand[] unevaluatedArguments = getArguments();
		List<AbstractXPathValue> evaluatedArguments = new ArrayList<AbstractXPathValue>(unevaluatedArguments.length);
		for (Operand unevaluatedArgument : unevaluatedArguments)
		{
			evaluatedArguments.add(unevaluatedArgument.evaluate(context));
		}
		try
        {
	        return function.execute(context, evaluatedArguments.toArray(new AbstractXPathValue[evaluatedArguments.size()]));
        }
        catch (XPathFunctionIllegalArgumentException e)
        {
	        throw new XPathEvaluationException("Failed to execute function: "+function.getName(), e);
        }
	}

}
